var path = require('path');
var fs = require('fs');
var formidable = require('formidable');
// var crypto = require('crypto');
var moment = require('moment');



/* 保存图片，成功后返回在图片服务器中的地址
 * 目前保存图片策略
 * 用户图片(比如证件）存放 /uploads/users/
 * 病例图片存放 /uploads/cases
 *
 * 路径命名规范： 日期  / 当前毫秒值+文件hash.xx
 * */
exports.saveUserImage = function (req, res) {
    console.log('--- saveUserImage ---');
    returnMsg = {};

    var curM = moment();
    var unix = curM.unix(); //时间戳
    var salt = generateSalt(); // 随机数

    //保存文件夹
    var monthFolder = curM.format("YYYY-MM"); //到月份
    var base64Data = '';
    if (req.body['format'] === 'png'){
        base64Data = req.body['image'].replace(/^data:image\/png;base64,/, "");
    }else if (req.body['format'] === 'jpg'){
        base64Data = req.body['image'].replace(/^data:image\/jpeg;base64,/, "");
    }
    // var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, req.body['image']);

    var imageName = salt + "-" + unix + "." + req.body['format']; //保存文件名

    var baseDir = "/Users/LeonTao/Downloads/uploads/";

    if (req.body['name'] === 'user'){ //用户图片
        baseDir = path.join(baseDir, "users/");
        if (!fs.existsSync(baseDir)){
            fs.mkdirSync(baseDir);
        }

        baseDir = path.join(baseDir, monthFolder);
        if (!fs.existsSync(baseDir)){
            fs.mkdirSync(baseDir);
        }
        // http://localhost:9000/resize?width=500&height=300&nocrop=true&file=users/2017-06/Hf5WsWuKK01498814198.png

        var baseSrc = "http://localhost:9000/resize?width=500&height=300&nocrop=true&file=users/" + monthFolder + "/";
        imgPath = baseDir + "/" + imageName;
        console.log("--- imgPath ---" + imgPath);
        //保存图片
        fs.writeFile(imgPath, base64Data, 'base64', function(err) {
            if(err){
                returnMsg['code'] = 0;
                returnMsg['msg'] = "上传图片出错";
                res.status(400).send(returnMsg);
            }else {
                returnMsg['code'] = 1;
                returnMsg['src'] = baseSrc + imageName;
                res.status(200).send(returnMsg);
            }
        });
    }
};



//删除图片
exports.deleteImage = function (req, res) {
    returnMsg = {};
    var baseDir = "/Users/LeonTao/Downloads/uploads/";
    //路径
    var imgPath = req.body['path'];
    imagePath = path.join(baseDir, imgPath);
    if (!fs.existsSync(imagePath)){
        returnMsg['code'] = 0;
        returnMsg['msg'] = "删除失败";
        res.status(400).send(returnMsg);
    }else{
        fs.unlink(imagePath, function(err){
            console.log(err);
        })
    }

};

exports.saveCaseImage = function (req, res, callback) {
    console.log('--- saveImage ---');

    returnMsg = {};

    // create an incoming form object
    var form = new formidable.IncomingForm();
    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;

    // store all uploads in the /uploads directory
    //应该保持到public文件夹下
    //获取当前周
    var curM = moment();
    var unix = curM.unix(); //时间戳
    var salt = generateSalt(); // 随机数

    //保存文件夹
    var folder = curM.format("YYYY-MM"); //到月份


    // var hash = crypto.createHash('md5').update(name).digest('hex'); //hash值

    // form.uploadDir = path.join('/Users/LeonTao/Downloads/uploads/', '/uploads'); //设置图片保存路径
    form.uploadDir = "/Users/LeonTao/Downloads/uploads/";
    var imgPath = '';
    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    form.on('file', function (field, file) {
        var fileName = salt + unix + file.name.split('.')[1]; //保存文件名
        if (file.name.split('.')[1] === 'user'){ //用户图片
            imgPath = "users/" + folder + "/" + file.name;
        }else{ //病例图片, 加上
            imgPath = "cases/" + folder + "/"+ String(curM.weeksInYear()) + "/" + file.name;
        }

        console.log('--- imgPath ---', imgPath);
        // fs.rename(file.path, path.join(form.uploadDir, file.name));
        fs.rename(file.path, path.join(form.uploadDir, imgPath));
    });

    // log any errors that occur
    form.on('error', function (err) {
        returnMsg['code'] = 0;
        returnMsg['msg'] = "上传图片出错";
        res.status(400).send(returnMsg);
    });

    // once all the files have been uploaded, send a response to the client
    form.on('end', function () {
        console.log('--- imgPath ---', imgPath)
        returnMsg['code'] = 1;
        returnMsg['src'] = imgPath;
        res.status(200).send(returnMsg);

    });

    // parse the incoming request containing the form data
    form.parse(req);

};

var generateSalt = function () {
    var set = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ';
    var salt = '';
    for (var i = 0; i < 10; i++) {
        var p = Math.floor(Math.random() * set.length);
        salt += set[p];
    }
    return salt;
};


